package com.hyt.it.ogt.kq.service.bm.mq;

import com.alibaba.fastjson.JSONObject;
import com.hyt.core.util.FastJsonUtil;
import com.hyt.it.ogt.kq.service.bm.model.dto.RegisterMessageDTO;
import com.hyt.it.ogt.kq.service.bm.service.ISendMessageService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;

/**
 * 推送消息消费者
 */

@Component
@Slf4j
public class SendMessageConsumer {

    @Resource
    private ISendMessageService iSendMessageService;

    @RabbitListener(
            bindings = {@QueueBinding(value = @Queue(value = "${mq.sendMessage.queue}",
                    autoDelete = "false", durable = "true"),
                    exchange = @Exchange(value = "${mq.direct}"),
                    key = {"${mq.sendMessage.route}"})},
            concurrency = "${mq.sendMessage.concurrency}")
    public void sendMessageListener(String jsonData, Message message, Channel channel) throws IOException {
        try {
            log.info("推送短信消息：{}", jsonData);
            List<RegisterMessageDTO> messageDTOList = FastJsonUtil.getJsonToList(jsonData, RegisterMessageDTO.class);
            iSendMessageService.sendMessage(messageDTOList);
        } catch (Exception e) {
            log.error("消息推送异常【{}】", JSONObject.toJSONString(jsonData), e);
        } finally {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        }
    }
}
